<?php
/**
 * Created by Engineer CuiLiwu.
 * Project: deal.
 * Date: 2018/6/12-13:58
 * License Hangzhou orce Technology Co., Ltd. Copyright © 2018
 */

namespace App\Http\Controllers\Web\Im;

use App\ConstDir\ErrorConst;
use App\Http\Controllers\Web\BaseController;
use Illuminate\Http\Request;

use App\Repository\Models\User;
use App\Repository\Repositories\Interfaces\UserImRepository;
use App\Repository\Repositories\Interfaces\UserImRecordRepository;
use App\Repository\Repositories\Interfaces\UserImNetcallRepository;

class ImController extends BaseController
{
    protected $request;
    protected $UserIm;
    protected $UserImRecord;
    protected $UserImNetcall;

    protected $api_url = [
        'create' => ['post', 'user/create.action'],
        'login'  => ['post', 'user/create.action'],
        'getContent'  => ['post', 'history/querySessionMsg.action'],
        'update' => ['post', '/user/updateUinfo.action'], // 更新用户信息 accid name icon sign email birth mobile gender ex
    ];

    protected $user_id;

    public function __construct(Request $request,UserImRepository $UserIm,UserImRecordRepository $UserImRecord,UserImNetcallRepository $UserImNetcall)
    {
        parent::__construct();
        $this->request = $request;
        $this->UserIm  = $UserIm;
        $this->UserImRecord  = $UserImRecord;
        $this->UserImNetcall = $UserImNetcall;
        $this->user_id = array_get($this->user, 'id');
    }
    /**
     * 登录验证 自动打开对话。
     * method post
     * url /
     * @return @json
     */
    public function login()
    {
        $this->validate($this->request, [
            'fuid' => 'required',
        ], [
            'fuid.required' => 'fuid 不可为空',
        ]);
        try {
            // 会话发起方 ID
            $id = $this->request->get('fuid');
            $info = $this->UserIm->findWhere(['user_id' => intval($id)]);
            if (isset($info['data'][0])) {
                $fromInfo = User::query()->where('id', $id)->first()->toArray();
                $info = $info['data'][0];
                $info['pic'] = $fromInfo['pic'];
                $tuid = intval($this->request->get('tuid')); // tuid 是shop_id 根据 shop_id 获取商家的 user_id

                // 会话接收方
                if ($tuid != null && $tuid != false) {
                    $to = User::query()->where('shop_id', $tuid)->first()->toArray();
                    $toIM = $this->UserIm->findWhere(['user_id' => $to['id']]);
                    if (isset($toIM['data'][0])) {
                        $toIM = $toIM['data'][0];
                        $info['to'] = $toIM;
                        $info['to']['pic'] = $to['pic'];
                    } else {
                        $info['to'] = false;
                    }
                }
            } else {
                return $this->error('获取信息失败', 599);
            }
        }catch (\Exception $e){
            return $this->error('获取信息失败', 598);
        }
        return $this->success(ErrorConst::SUCCESS_CODE,$info);
    }

    /**
     * 创建新的 IM 用户
     * method post
     * url /
     * @return @json
     */
    public function store()
    {
        $data = $this->form();
        // IM 创建用户
        $imCreate =http_im($this->api_url['create'])->send($data);
        if ($imCreate['code']!=200){
            return $this->error('注册失败', $imCreate['code']);
        }

        $imCreate['info']['user_id'] = $this->user_id;
        $imCreate['info']['password'] = md5($data['password']);
        // 本地数据库存储
        $create = $this->UserIm->updateOrCreate($imCreate['info']);

        return $this->success(ErrorConst::SUCCESS_CODE,$create);
    }
    /**
     * 根据用户 id 获取 im 用户信息
     * method post
     * url /
     * @return @json
     */
    public function getImInfo($id)
    {
        $ImInfo = $this->UserIm->findWhere(['user_id'=>$id]);

        return $this->success(ErrorConst::SUCCESS_CODE,$ImInfo);
    }
    /**
     * 验证传入的值
     * @return @array
     */
    public function form()
    {
        $this->validate($this->request, [
            'accid' => 'required',
            'name' => 'required',
            'password' => 'required',
        ], [
            'accid.required' => 'accid 不可为空',
            'name.required' => '昵称不可为空',
            'password.required' => '密码不可为空',
        ]);
        return $this->request->all(['accid','name','password']);
    }
    /**
     * 账号密码登录
     * @return @array
     */
    public function loginAccount()
    {
        $this->validate($this->request, [
            'username' => 'required',
            'password' => 'required',
        ], [
            'accid.required' => '登录账号不可为空',
            'password.required' => '密码不可为空',
        ]);
        $username = $this->request->get('username');

        $info = $this->UserIm->findWhere(['accid'=>$username]);
        if (isset($info['data'][0])) {
            $user = $info['data'][0];
            // md5 密码验证
            $password = md5($this->request->get('password'));
            if ($user['password']==$password){
                return $this->success(ErrorConst::SUCCESS_CODE,$user);
            }else{
                return $this->error('账号或密码错误',598);
            }

        }else{
            return $this->error('账号或密码错误',599);
        }
    }
    /**
     * 储存聊天信息 / 接口预留，储存聊天信息实际执行处为ImListener
     * @return @array
     */
    public function saveImContent()
    {
        $data = $this->request->all(['from','to','begintime','limit','endtime']);

        $this->validate($this->request, [
            'from' => 'required',
            'to' => 'required',
            'begintime' => 'required',
        ], [
            'from.required' => '发送者accid 不可为空',
            'to.required' => '接收者accid不可为空',
            'begintime.required' => '开始时间不可为空',
        ]);

        $params = [
            'from'=> $data['from'],
            'to'  => $data['to'],
            'begintime' => $data['begintime'].'000',
            'endtime'   => isset($data['endtime'])?$data['endtime']:intval(time().'000'),
            'limit'     => isset($data['limit'])?intval($data['limit']):100,
            'reverse'   => 2, // 1按时间正序排列，2按时间降序排列。其它返回参数414错误.默认是按降序排列
        ];
        $content = http_im($this->api_url['getContent'])->send($params);

        return $this->success(ErrorConst::SUCCESS_CODE,$content);
    }
    /**
     * 储存两个用户已发起的聊天。
     * 在监听事件中查询储存后会删除。下次点开会话的时候会重新添加。
     * @return @array
     */
    public function recordRelation()
    {
        $data = $this->request->all(['accid_a','accid_b']);
        $create = [];
        try {
            // 检测 用户是否存储于在 user_im 中存在
            $this->validate($this->request, [
                'accid_a' => 'required|exists:user_im,accid',
                'accid_b' => 'required|exists:user_im,accid',
            ], [
                'accid_a' => 'accid_a 不可为空|accid_a 不合法',
                'accid_b' => 'accid_b 不可为空|accid_b 不合法',
            ]);

            $params = [
                'accid_a' => $data['accid_a'],
                'accid_b' => $data['accid_b'],
            ];
            // 记录聊天表
            $create = $this->UserImNetcall->updateOrCreate($params, [
                'accid_a' => $data['accid_a'],
                'accid_b' => $data['accid_b'],
                'updated_at' => date('Y-m-d H:i:s', time())
            ]);
        }catch (\Exception $e){
            return $this->error($e->getMessage(),599);
        }
        return $this->success(ErrorConst::SUCCESS_CODE,$create);
    }

    /**
     * 根据用户 id 获取 im 用户信息
     * method post
     * url /
     * @return @json
     */
    public function userImCheck($user_id)
    {
        if (!isset($user_id)||$user_id==null||$user_id==''){
            return $this->error('参数错误',599);
        }else {
            $checkInfo = $this->UserIm->userImCheck($user_id);
        }
        return $this->success(ErrorConst::SUCCESS_CODE,$checkInfo);
    }

    /**
     *  accid	String	是	用户帐号，最大长度32字符，必须保证一个APP内唯一
     *  name	String	否	用户昵称，最大长度64字符
     *  icon	String	否	用户头像，最大长度1024字节
     *  sign	String	否	用户签名，最大长度256字符
     *  email	String	否	用户email，最大长度64字符
     *  birth	String	否	用户生日，最大长度16字符
     *  mobile  String	否	用户mobile，最大长度32字符
     *  gender   int	否	用户性别，0表示未知，1表示男，2女表示女，其它会报参数错误
     *  ex      String	否	用户名片扩展字段，最大长度1024字符，用户可自行扩展，建议封装成JSON字符串
     **/
    public function update(){
        $data = $this->request->all(['accid','name','icon','sign','email','birth','mobile','gender','ex']);

        $this->validate($this->request, [
            'accid'  => 'required',
            'name'   => 'max:64',
            'icon'   => 'max:1024',
            'email'  => 'email|max:64',
            'birth'  => 'max:16',
            'mobile' => 'regex:/^1[345789][0-9]{9}$/',
            'gender' => 'in:0,1,2',
            'ex'     => 'max:1024',
        ], [
            'accid.required'  => 'accid 不可为空',
            'name.required'   => 'name 最大长度为64字符',
            'icon.required'   => 'icon 最大长度为1024字符',
            'email.required'  => 'email格式不正确|email最大长度为64字符',
            'birth.required'  => 'birth最大长度为16字符',
            'mobile.required' => 'mobile格式不正确',
            'gender.required' => 'gender格式不正确',
            'ex.required'     => 'ex 最大长度为1024字符',
        ]);

        $params = [
            'accid'  => $data['accid'],
            'name'   => $data['name'],
            'icon'   => $data['icon'],
            'email'  => $data['email'],
            'birth'  => $data['birth'],
            'mobile' => $data['mobile'],
            'gender' => $data['gender'],
            'ex'     => $data['ex'],
        ];
        $content = ['Expected modify information is null . But accid only given.'];
        $params = array_filter($params);
        if (count($params)>1){
            $content = http_im($this->api_url['update'])->send($params);
        }

        return $this->success(ErrorConst::SUCCESS_CODE,$content);
    }
}